const AppDispatcher = require('../dispatcher/AppDispatcher')
const EventEmitter = require('events').EventEmitter
const TodoConstants = require('../constants/TodoConstants')
const assign = require('object-assign')

const CHANGE_EVENT = 'change'

const _todos = {}

function create(text) {
  const id = (+new Date() + Math.floor(Math.random() * 999999)).toString(36)
  _todos[id] = {
    id: id,
    complete: false,
    text: text
  }
}
function update(id, updates) {
  _todos[id] = assign({}, _todos[id], updates)
}

const TodoStore = assign({}, EventEmitter.prototype, {
  getAll: function() {
    return _todos
  },
  emitChange: function() {
    this.emitChange(CHANGE_EVENT)
  },
  addChangeListener: function(callback) {
    this.on(CHANGE_EVENT, callback)
  }
})

AppDispatcher.register(function(action) {
  let text

  switch(action.actionType) {
    case TodoConstants.TODO_CREATE:
      text = action.text.trim()
      if (text !== '') {
        create(text)
      }
      TodoStore.emitChange()
      break
      
    case TodoConstants.TODO_UPDATE_TEXT:
      text = action.text.trim()
      if (text != '') {
        update(action.id, {text: text})
      }
      TodoStore.emitChange()
      break
  }
})
